import { defineStore } from "pinia"
import {
    requestCategory1List,
    requestCategory2List,
    requestCategory3List,
} from "@/api/attr"
import type { reqCategory1ListReturnType } from "@/api/attr"
import { ElMessage } from "element-plus";


//定义state数据类型
interface stateType {
    categoryList1: reqCategory1ListReturnType;
    categoryList2: reqCategory1ListReturnType;
    categoryList3: reqCategory1ListReturnType;
    category1Id: number | null;
    category2Id: number | null;
    category3Id: number | null;
}

//创建AttrList小仓库
const useAttrListStore = defineStore("useAttrListStore", {
    state: (): stateType => {
        return {
            /* 列表用于渲染视图,id用来请求列表数据 */
            categoryList1: [],
            categoryList2: [],
            categoryList3: [],
            /* 
            如果直接给默认值,默认值会直接展示在输入框中
            但是请求回来的id是number类型
            解决:
              使用null进行初始化
            */
            category1Id: null,
            category2Id: null,
            category3Id: null,
        }
    },
    getters: {

    },
    actions: {
        //请求一级分类数据
        async getCategory1() {
            try {
                //发送一级分类请求
                const result = await requestCategory1List()
                this.categoryList1 = result
            } catch (e) {
                ElMessage.error("请求一级分类失败")
            }
        },

        //请求二级分类
        async getCategory2() {
            try {
                //发送一级分类请求
                const result = await requestCategory2List(this.category1Id as number)
                this.categoryList2 = result
            } catch (e) {
                ElMessage.error("请求二级分类失败")
            }
        },
        //请求三级分类
        async getCategory3() {
            try {
                //发送一级分类请求
                const result = await requestCategory3List(this.category2Id as number)
                this.categoryList3 = result
            } catch (e) {
                ElMessage.error("请求三级分类失败")
            }
        },
    },

})

export default useAttrListStore